//index.js
var app = getApp();
Page({
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    modalName:'',
    painting: {},
    painting2: {},
    shareImage: '',
    detail: '',
    userInfo: '',
    id: '',
    imgurl: ''
  },
  onLoad(options) {
    var _this = this;
    var id = options.id;
    //  var userinfomation = wx.getStorageSync('user_info')
    console.log(id)
    _this.setData({
      id: id,
    })
    var openid = getApp().globalData.openid;
    if (!openid) {
      wx.showModal({
        title: '提示',
        content: '本功能需要授权后才可使用，点击确定跳转到登录界面',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
           _this.showModal()
          } else if (res.cancel) {
            console.log('用户点击取消')
            wx.navigateBack()
          }
        }
      })
      return;
    } else {
      this.loadDetail()
    }

    // setTimeout(() => {

    // }, 1000)
  },

  loadDetail() {
    var _this = this;
    var id = this.data.id;
    var openid = getApp().globalData.openid

    app.core('get', 'newhouse/getLoupanCode', { open_id: openid, id: id }, (res) => {
      console.log(res)
      _this.setData({
        detail: res.data
      })
      var url = res.data.buildNoPhoto;
      var id = res.data.id;
      var code = res.data.code;
      console.log(code)
      var imgU = url.replace('http', 'https')
      var imgUrl = imgU.replace('com', 'cn')
      _this.setData({
        imgurl: imgUrl,
        code: code
      })

      _this.eventDraw()
    })
  },
  onShow() {
  },
  eventDraw(bgImage) {
    wx.showLoading({
      title: '绘制海报中...',
      mask: true
    })
    var userinfomation = wx.getStorageSync('userInfo');
    var imgurl = this.data.imgurl;
    var code = this.data.code;
    var detail = this.data.detail;

    console.log(imgurl)
    if (bgImage == undefined || bgImage == '') {
      bgImage = 'https://xkcloude.hfhouse.com/storage/advert/2019-09-03/6ePMy2tJffkU6XwA6y7GdIe05MISj1lT3p0C1DFm.png';
      var painting = {
        width: 375,
        height: 555,
        clear: true,
        views: [
          {
            type: 'image',
            url: bgImage,
            top: 0,
            left: 0,
            width: 375,
            height: 555
          },
          {
            type: 'image',
            url: userinfomation.avatarUrl,
            top: 27.5,
            left: 29,
            width: 55,
            height: 55
          },
          {
            type: 'image',
            url: 'https://xkcloude.hfhouse.com/storage/advert/2019-09-04/GtLogXoFwh5lpetAlbd1Dkd7YcZ74B4YCuz2K2lW.png',
            top: 27.5,
            left: 29,
            width: 55,
            height: 55
          },
          {
            type: 'text',
            content: userinfomation.nickName + '   在星房惠小程序',
            fontSize: 16,
            color: '#FBFBFB',
            textAlign: 'left',
            top: 33,
            left: 96,
            bolder: true
          },
          {
            type: 'text',
            content: '发现一处好楼盘，快来看看',
            fontSize: 16,
            color: '#FBFBFB',
            textAlign: 'left',
            top: 59.5,
            left: 96
          },
          {
            type: 'image',
            url: imgurl,
            top: 116,
            left: 42.5,
            width: 290,
            height: 186
          },
          {
            type: 'image',
            url: code,
            top: 433,
            left: 55,
            width: 82,
            height: 82
          },
          {
            type: 'text',
            content: detail.projectName,
            fontSize: 20,
            lineHeight: 21,
            color: '#2665EC',
            textAlign: 'left',
            top: 316,
            left: 44,
            width: 287,
            MaxLineNumber: 2,
            breakWord: true,
            bolder: true
          },
          {
            type: 'text',
            content: detail.projectAddr,
            fontSize: 16,
            lineHeight: 21,
            color: '#383549',
            textAlign: 'left',
            top: 344,
            left: 44,
            width: 287,
            MaxLineNumber: 2,
            breakWord: true,
            bolder: true
          },
          {
            type: 'text',
            content: detail.averagePrice ? detail.averagePrice  : '待定',
            fontSize: 20,
            color: '#E62004',
            textAlign: 'left',
            top: 385,
            left: 44,
            bolder: true
          },
          {
            type: 'text',
            content: detail.build_feat_txt,
            fontSize: 13,
            color: '#383549',
            textAlign: 'left',
            top: 388,
            left: 155,
          },
          // {
          //   type: 'text',
          //   content: detail.junior_school.name,
          //   fontSize: 13,
          //   color: '#383549',
          //   textAlign: 'left',
          //   top: 390,
          //   left: 155,
          //   width: 180,
          //   breakWord: true,
          // },
          // {
          //   type: 'text',
          //   content: detail.middle_school.name,
          //   fontSize: 13,
          //   color: '#383549',
          //   textAlign: 'left',
          //   top: 410,
          //   left: 155,
          //   width: 180,
          //   breakWord: true,
          // },
          {
            type: 'text',
            content: '识别小程序二维码',
            fontSize: 14,
            color: '#383549',
            textAlign: 'left',
            top: 460,
            left: 165.5,
            lineHeight: 20,
            width: 125
          },
          {
            type: 'text',
            content: '进入星房惠查看楼盘',
            fontSize: 14,
            color: '#383549',
            textAlign: 'left',
            top: 480,
            left: 165.5,
            lineHeight: 20,
            width: 125
          }
        ]
      }
    } else {
      var painting = {
        width: 500,
        height: 889,
        clear: true,
        views: [
          {
            type: 'image',
            url: bgImage,
            top: 0,
            left: 0,
            width: 500,
            height: 889,
          },
          // {
          //     type: 'image',
          //     url: userinfomation.avatarUrl,
          //     top: 27.5,
          //     left: 29,
          //     width: 55,
          //     height: 55
          // },
          // {
          //     type: 'text',
          //     content: userinfomation.nickName,
          //     fontSize: 16,
          //     color: '#FBFBFB',
          //     textAlign: 'left',
          //     top: 33,
          //     left: 96,
          //     bolder: true
          // },
          {
            type: 'image',
            url: code,
            top: 739,
            left: 350,
            width: 95,
            height: 95
          },
          {
            type: 'text',
            content: '星房惠小程序',
            fontSize: 16,
            color: '#FBFBFB',
            textAlign: 'left',
            top: 720,
            left: 350,
            bolder: true
          }
        ]
      }
    }


    this.setData({
      painting: painting
    })

    var painting2 = {
      width: 300,
      height: 300,
      clear: true,
      views: [
        {
          type: 'image',
          url: code,
          top: 0,
          left: 0,
          width: 300,
          height: 300
        }
      ]
    }

    this.setData({
      painting2: painting2
    })
  },
  eventSave() {
    var id = this.data.id;
    console.log(id)
    // console.log(this.data.shareImage)
    // let _this = this;
    wx.saveImageToPhotosAlbum({
      filePath: this.data.shareImage,
      success(res) {
        wx.showToast({
          title: '保存图片成功',
          icon: 'success',
          duration: 2000
        })
        setTimeout(function () {
          wx.navigateTo({
            url: '/pages/loupan/detail?id=' + id,
          });
        }, 1000)
      },
      fail(err) {
        if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
          // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
          wx.showModal({
            title: '提示',
            content: '需要您授权保存相册',
            showCancel: false,
            success: modalSuccess => {
              wx.openSetting({
                success(settingdata) {
                  console.log("settingdata", settingdata)
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    wx.showModal({
                      title: '提示',
                      content: '获取权限成功,再次点击图片即可保存',
                      showCancel: false,
                    })
                  } else {
                    wx.showModal({
                      title: '提示',
                      content: '获取权限失败，将无法保存到相册哦~',
                      showCancel: false,
                    })
                  }
                },
                fail(failData) {
                  console.log("failData", failData)
                },
                complete(finishData) {
                  console.log("finishData", finishData)
                }
              })
            }
          })
        }
      },
    })
  },
  eventCodeImgSave() {
    if (this.data.codeImage) {
      wx.saveImageToPhotosAlbum({
        filePath: this.data.codeImage,
        success(res) {
          wx.showToast({
            title: '保存图片成功',
            icon: 'success',
            duration: 2000
          })
          console.log(err)
          setTimeout(function () {
            wx.navigateTo({
              url: '/pages/loupan/detail?id=' + id,
            });
          }, 1000)
        },
        fail(err) {
          console.log(err)
          if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
            // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
            wx.showModal({
              title: '提示',
              content: '需要您授权保存相册',
              showCancel: false,
              success: modalSuccess => {
                wx.openSetting({
                  success(settingdata) {
                    console.log("settingdata", settingdata)
                    if (settingdata.authSetting['scope.writePhotosAlbum']) {
                      wx.showModal({
                        title: '提示',
                        content: '获取权限成功,再次点击图片即可保存',
                        showCancel: false,
                      })
                    } else {
                      wx.showModal({
                        title: '提示',
                        content: '获取权限失败，将无法保存到相册哦~',
                        showCancel: false,
                      })
                    }
                  },
                  fail(failData) {
                    console.log("failData", failData)
                  },
                  complete(finishData) {
                    console.log("finishData", finishData)
                  }
                })
              }
            })
          }
        },
      })
    }
  },
  eventGetImage(event) {
    console.log(event)
    wx.hideLoading()
    const { tempFilePath, errMsg } = event.detail
    if (errMsg === 'canvasdrawer:ok') {
      this.setData({
        shareImage: tempFilePath
      })
    }
  },
  eventGetImage2(event) {
    const { tempFilePath, errMsg } = event.detail
    if (errMsg === 'canvasdrawer:ok') {
      this.setData({
        codeImage: tempFilePath
      })
    }
  },
  previewImg(e) {
    var current = e.target.dataset.src;
    console.log(current)
    wx.previewImage({
      current: current,
      urls: [this.data.shareImage]
    })
  },
  selectImage() {
    var that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths)
        that.eventDraw(tempFilePaths[0])
      }
    })
  },

  showModal(e) {
    this.setData({
      modalName: 'DialogModal1'
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
    wx.navigateBack()
  },
  getUserInfo: function (e) {
    console.log(e)
    var vm = this;
    var UserInfo = e.detail.userInfo
    // wx.setStorageSync('userInfo', e.detail.userInfo)
    wx.login({
      success(res) {
        console.log(res)
        if (res.code) {
          var userCode = res.code;
          var referrer = wx.getStorageSync('referrer')
          app.core('post', 'create_xcx_user', {
                'nickname': UserInfo.nickName,
                'headpic': UserInfo.avatarUrl,
                'js_code': userCode,
                'referrer': referrer
              }, (res) => {
                console.log(res)
                // return false
                console.log("open_id" + res.data.open_id);
                wx.setStorageSync('userInfo', e.detail.userInfo);
                console.log(wx.getStorageSync('userInfo'));
                wx.setStorageSync('user_new', res.data.open_id);
                wx.setStorageSync('sessionKey', res.sessionKey);
                console.log(wx.getStorageSync('user_new'))

                getApp().globalData.openid = res.data.open_id

                vm.setData({
                  userInfo: e.detail.userInfo,
                  hasUserInfo: true,
                  isMain: true,
                  isPower: wx.getStorageSync('user_new')
                });
                wx.hideLoading()
                vm.setData({
                  modalName: null
                })

                vm.loadDetail()
              },
              (err) => {
                console.log(err)
              }
          )

        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    });
  },

  // share() {
  //   wx.updateShareMenu({
  //     withShareTicket: true,
  //     success(res) {
  //       console.log(res)
  //     }
  //   })
  // }
})
